package com.demo.cms.action.manage;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.struts2.util.ServletContextAware;

import com.demo.Constants;
import com.demo.common.StringUtils;
import com.demo.common.Utils;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.dao.base.support.SearchArgumentSupport;
import com.demo.core.model.Site;
import com.demo.core.model.Template;
import com.demo.core.service.base.TemplateService;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;
import com.demo.webapp.context.MultisiteContextHolder;
import com.demo.webapp.views.freemarker.directive.config.ConfigurationManager;
import com.demo.webapp.views.freemarker.directive.model.DirectiveGroupModel;

/**
 * 模板管理
 * @author ryuu.kk
 *
 */
@Function(id = 101300, pid = 10, code = "manage.template")
public class TemplateAction extends PageAction implements ServletContextAware {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -2804783960188512799L;

	/**
	 * 模板服务
	 */
	private TemplateService templateService;
	
	/**
	 * Servlet上下文
	 */
	private ServletContext context;
	
	/**
	 * 模板ID
	 */
	private Long id;
	
	/**
	 * 频道ID
	 */
	private Long channelId;
	
	/**
	 * 模板类型
	 */
	private String type;

	/**
	 * 模板模型
	 */
	private Template template;
	
	/**
	 * 模板列表
	 */
	private List<Template> templateList;
	
	/**
	 * 自定义指令集
	 */
	private List<DirectiveGroupModel> directiveGroupModelList;
	
	/**
	 * 同步写入数据库
	 */
	private Boolean isSynchDb = Boolean.TRUE;
	
	
	private List<String[]> typeList = new ArrayList<String[]>(){/** **/
		private static final long serialVersionUID = 8831055660870347106L;
	{
		// 频道
		add(new String[]{getText("template.type." + Constants.TYPE_CHANNEL), Constants.TYPE_CHANNEL});
		add(new String[]{getText("template.type." + Constants.TYPE_CATEGORY), Constants.TYPE_CATEGORY});
		add(new String[]{getText("template.type." + Constants.TYPE_ARTICLE), Constants.TYPE_ARTICLE});
		add(new String[]{getText("template.type." + Constants.TYPE_OTHER), Constants.TYPE_OTHER});
	}};
	/**
	 * 初始页
	 * @return resultMap
	 */
	@Function(id = 101301, pid = 101300, code = "manage.template.execute")
	public String execute() {
		
		return SUCCESS;
	}
	
	/**
	 * 模板列表
	 * @return resultMap
	 */
	@Function(id = 101310, pid = 101300, code = "manage.template.list")
	public String list() {
		//取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		
		SearchArgumentSupport args = getArgumentSupport();
		//由于模板数量较少(至多不超过50),直接取得最大结果集,由view层分页
		args.setMaxResults(Integer.MAX_VALUE);
		// 分页查询, 不包含模板内容
		ResultSearchResult<Template> result = templateService.search(siteId, type, false, args);
		this.setResultSupport(result);
		this.templateList = new ArrayList<Template>(result.getResults());
		
		return SUCCESS;
	}
	
	/**
	 * 模板创建
	 * @return resultMap
	 */
	@Function(id = 101320, pid = 101300, code = "manage.template.create")
	public String create() {
		
		// 取得自定义指令集合
		ConfigurationManager manager = ConfigurationManager.getInstance();
		directiveGroupModelList = manager.getDirectiveGroupModelList();
		return SUCCESS;
	}
	
	/**
	 * 模板保存
	 * @return resultMap
	 */
	@Function(id = 101330, pid = 101300, code = "manage.template.save")
	public String save() {
		
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		template.setSiteId(siteId);
		// 模板资源路径resPath
		String resPath = getResPath(site);

		if (StringUtils.isEmpty(type)) {
			type = "default";
		}
		// 模板存储路径
		// edit by ryuu.kk at 2012-12-24 使用站点资源res_path资源进行统一
		//template.setPath(Constants.TEMPLATE_HOME + Utils.uuid());
		template.setPath(Constants.TEMPLATE_HOME + type + "/" + Long.toHexString(Utils.uuidShort()) + "." + site.getSuffix());
		// 创建成功后,同步本地文件夹
		String templatePath = context.getRealPath(resPath + template.getPath());
		try {
			StringUtils.textWriter(new StringBuffer(template.getContent()), (new File(templatePath)).toURI(), 2);
		} catch (IOException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
		// 如果内容不需要同步数据,则清除
		if (!isSynchDb) {
			template.setContent("");
		}
		templateService.save(template);
		
		addActionMessage(getText("模板保存成功."));
		return CALLBACK;
	}
	
	/**
	 * 模板编辑
	 * @return resultMap
	 */
	@Function(id = 101340, pid = 101300, code = "manage.template.edit")
	public String edit() {
		
		//templateService.update(template.getId(), template.getName(), template.getPath(), template.getContent());
		this.template = templateService.find(id, false);
		// 模板资源路径resPath
		String resPath = getResPath(getSite()) + template.getPath();
		resPath = context.getRealPath(resPath);
		File templateFile = new File(resPath);
		if (!templateFile.exists()){
			// 本地模板文件不存在
			this.template = templateService.find(id, true);
			URI uri = (new File(resPath)).toURI();
			try {
				if (template.getContent() != null) {
					StringUtils.textWriter(new StringBuffer(template.getContent()), uri, 0);
				}
			} catch (IOException e) {
				addActionError(e.getMessage());
				return CALLBACK;
			}
		} else {
		    if (templateFile.canRead()) {
		    	// 本地模板文件存在
				StringBuffer sb = StringUtils.textReader(templateFile.toURI());
				template.setContent(sb.toString());
		    }
		}
		// 取得自定义指令集合
		ConfigurationManager manager = ConfigurationManager.getInstance();
		directiveGroupModelList = manager.getDirectiveGroupModelList();
		return SUCCESS;
	}
	
	/**
	 * 模板编辑
	 * @return resultMap
	 */
	@Function(id = 101350, pid = 101300, code = "manage.template.update")
	public String update() {
		Template temp = templateService.find(template.getId(), false);
		if (temp == null) {
			addActionError(getText("未找到模板"));
			return CALLBACK;
		}
		
		// 模板资源路径resPath
		String resPath = getResPath(getSite()) + temp.getPath();
		// 创建成功后,同步本地文件夹
		String templatePath = context.getRealPath(resPath);
		try {
			// 新建文件
			StringUtils.textWriter(new StringBuffer(template.getContent()), (new File(templatePath)).toURI(), 0);
		} catch (IOException e) {
			addActionError(e.getMessage());
			return INPUT;
		}
		// 如果内容不需要同步数据,则清除
		if (!isSynchDb) {
			template.setContent("");
		}
		templateService.update(template.getId(), template.getName(), template.getPath(), template.getContent());
		
		addActionMessage(getText("模板更新成功."));
		return CALLBACK;
	}
	
	/**
	 * 模板删除
	 * @return resultMap
	 */
	@Function(id = 101360, pid = 101300, code = "manage.template.delete")
	public String delete() {
		// 清除本地模板
		Template template = templateService.find(id, false);
		if (template == null) {
			addActionMessage(getText("模板不存在."));
			return CALLBACK;
		}
		// 模板资源路径resPath
		String resPath = getResPath(getSite()) + template.getPath();
		// 模板资源路径resPath(绝对路径)
		String templatePath = context.getRealPath(resPath);
		File file = new File(templatePath);
		if (file.exists()) {
			file.delete();
		}
		// 如果内容不需要同步数据,则清除
		if (isSynchDb) {
			templateService.delete(id);
		}
		addActionMessage(getText("模板删除成功."));
		return CALLBACK;
	}
	
	public Long getChannelId() {
		return channelId;
	}

	public void setChannelId(Long channelId) {
		this.channelId = channelId;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getType() {
		return type;
	}

	public Template getTemplate() {
		return template;
	}

	public void setTemplate(Template template) {
		this.template = template;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public List<DirectiveGroupModel> getDirectiveGroupModelList() {
		return directiveGroupModelList;
	}

	public List<Template> getTemplateList() {
		return templateList;
	}

	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}

	public List<String[]> getTypeList() {
		return typeList;
	}

	@Override
	public void setServletContext(ServletContext context) {
		this.context = context;
	}
	
	/**
	 * 取得站点资源路径
	 * @param site Site
	 * @return String
	 */
	protected String getResPath(Site site) {
		String resPath = site.getResPath();
		if (StringUtils.isEmpty(resPath)) {
			resPath = (String) getConfiguration().get(com.demo.webapp.config.Constants.PUBLISH_FOLDER_KEY);
		}
		resPath.replace("\\", "/");
		if (resPath.charAt(0) != '/' ) {
			resPath = "/" + resPath;
		}
		if (resPath.charAt(resPath.length() - 1) != '/') {
			resPath += "/";
		}
		return resPath;
	}
}